package com.xm.dao.impl;

import com.xm.dao.SearchHistoryDao;
import com.xm.po.SearchHistory;
import com.xm.util.BaseDao;
import com.xm.util.DButil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author Administrator
 * @date 2020-08-07-15:36
 * @description 搜索历史数据接口实现类
 */
public class SearchHistoryDaoImpl implements SearchHistoryDao {
    @Override
    public boolean add(SearchHistory searchHistory) {
        return DButil.insert(searchHistory);
    }

    @Override
    public List<SearchHistory> getSearchHistoryTop5(Integer userId) {
        Connection conn = DButil.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<SearchHistory> histories = null;
        String sql = "select * from searchhistory where userId = ? order by count limit 5";
        try {
            ps = conn.prepareStatement(sql);
            ps.setObject(1,userId);
            rs = ps.executeQuery();
            histories = (List<SearchHistory>) DButil.getRsData(SearchHistory.class,rs);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DButil.close(rs,ps,conn);
        }
        return histories;
    }

    @Override
    public SearchHistory getSearchHistoryByUid(Integer userId, String key) {
        Connection conn = DButil.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        SearchHistory searchHistory = new SearchHistory();
        String sql = "select * from searchhistory where userId = ? and searchKey = ?";
        try {
            ps = conn.prepareStatement(sql);
            ps.setObject(1,userId);
            ps.setObject(2,key);
            rs = ps.executeQuery();
            searchHistory = (SearchHistory) DButil.getRsOne(SearchHistory.class,rs);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DButil.close(rs,ps,conn);
        }
        return searchHistory;
    }

    @Override
    public boolean update(SearchHistory searchHistory) {
        Connection conn = DButil.getConnection();
        PreparedStatement ps = null;
        String sql = "update searchhistory set count = ? where id = ?";
        try {
            ps = conn.prepareStatement(sql);
            ps.setObject(1,searchHistory.getCount());
            ps.setObject(2,searchHistory.getId());
            return ps.executeUpdate()>0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }
}
